const path = require('path')
const MiniCSSExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { DefinePlugin } = require('webpack')
let config = {
  devServer: {
    static: './dist'
  },
  entry: {
    login: path.resolve(__dirname, 'src/login/index.js'),
    content: path.resolve(__dirname, 'src/content/index.js'),
    publish: path.resolve(__dirname, 'src/publish/index.js')
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name]/index.js',
    clean: true,
    assetModuleFilename: 'assets/[hash]_[query]_[ext]'
  },
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [process.env.NODE_ENV === 'development' ? 'style-loader' : MiniCSSExtractPlugin.loader, 'css-loader']
      },
      {
        test: /\.(jpg|svg|png|jpeg|gif)$/i,
        type: 'asset'
      }
    ]
  },
  optimization: {
    minimizer: [`...`, new CssMinimizerPlugin()],
    splitChunks: {
      chunks: 'all', // 所有模块动态非动态移入的都分割分析
      cacheGroups: {
        // 分隔组
        commons: {
          // 抽取公共模块
          minSize: 0, // 抽取的chunk最小大小字节
          minChunks: 2, // 最小引用数
          reuseExistingChunk: true, // 当前 chunk 包含已从主 bundle 中拆分出的模块，则它将被重用
          name(module, chunks, cacheGroupKey) {
            // 分离出模块文件名
            const allChunksNames = chunks.map((item) => item.name).join('~') // 模块名1~模块名2
            return `./common/${allChunksNames}` // 输出到 dist 目录下位置
          }
        }
      }
    }
  },
  plugins: [
    new MiniCSSExtractPlugin({
      // output+这里的filename
      filename: './[name]/index.css'
    }),
    new DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    }),
    new CssMinimizerPlugin(),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'public/login.html'),
      filename: path.resolve(__dirname, 'dist/login/login.html'),
      useCDN: process.env.NODE_ENV == 'production',
      chunks: ['login']
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'public/content.html'),
      filename: path.resolve(__dirname, 'dist/content/content.html'),
      useCDN: process.env.NODE_ENV == 'production',
      chunks: ['content']
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'public/publish.html'),
      filename: path.resolve(__dirname, 'dist/publish/publish.html'),
      useCDN: process.env.NODE_ENV == 'production',
      chunks: ['publish']
    })
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  }
}

if (process.env.NODE_ENV === 'development') {
  config.devtool = 'inline-source-map'
}

// 生产环境下使用相关配置
if (process.env.NODE_ENV === 'production') {
  // 外部扩展（让 webpack 防止 import 的包被打包进来）
  config.externals = {
    // key：import from 语句后面的字符串
    // value：留在原地的全局变量（最好和 cdn 在全局暴露的变量一致）
    'bootstrap/dist/css/bootstrap.min.css': 'bootstrap',
    axios: 'axios',
    'form-serialize': 'serialize',
    '@wangeditor/editor': 'wangEditor'
  }
}
module.exports = config
